package com.zhupf.springcloud.controller;

import com.zhupf.springcloud.entity.CommonResult;
import com.zhupf.springcloud.entity.Payment;
import com.zhupf.springcloud.lb.LoadBalancer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private DiscoveryClient discoveryClient;

    @Autowired
    private LoadBalancer loadBalancer;

    public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";

    @PostMapping("/create")
    public CommonResult create(@RequestBody Payment payment){
        return restTemplate.postForObject(PAYMENT_URL+"/payment/create",payment,CommonResult.class);
    }

    @GetMapping("info/{id}")
    public CommonResult<Payment> info(@PathVariable("id") Long id){
        return restTemplate.getForObject(PAYMENT_URL+"/payment/info/"+id,CommonResult.class);
    }

    @GetMapping("getIbPort")
    public String getPort(){
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        ServiceInstance serviceInstance = loadBalancer.getServiceInstance(instances);
        return restTemplate.getForObject(serviceInstance.getUri()+"/payment/port",String.class);
    }



}
